package weixin.util;

import java.util.Date;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import base.model.exception.BizHandleException;
import base.util.HttpRequestUtils;
import mt.Const;
import weixin.model.WeiXinUser;

public class WxUserInfoProvider {

	private static final Logger LOG = Logger.getLogger(WxUserInfoProvider.class);

	private static WxUserInfoProvider wxUserInfoProvider;

	private WxUserInfoProvider() {

	}

	public static synchronized WxUserInfoProvider getInstance() {
		if (wxUserInfoProvider == null) {
			wxUserInfoProvider = new WxUserInfoProvider();
		}
		return wxUserInfoProvider;
	}

	/**
	 *
	 * {"subscribe":1,"openid":"o0X2Dt8jj3izbrULSC8VqGXHxVI4","nickname":"生银",
	 * "sex":1,"language":"en",
	 * "city":"长沙","province":"湖南","country":"中国","headimgurl":
	 * "http:\/\/wx.qlogo.cn\/mmopen\/ajNVdqHZLLCRR7Tr7XnAEHUVGLAM5oszp0mas50gial2SIFZbqBPBT70kA3MkThZEBMicKaSplJYq6zoiafs57iatA\/0"
	 * ,"subscribe_time":1453268388,"remark":"","groupid":0}**
	 * 
	 * @param openid
	 * @return
	 */
	public WeiXinUser queryWxUserInfo(String openid) {
		try {

			String accessToken = WxAccessTokenProvider.getInstance().getAccessToken();

			String api = Const.WEIXIN_USER_INFO_URL_TPL.replace("{token}", accessToken).replace("{openId}", openid);

			String response = HttpRequestUtils.doGetSSL(api);

			JSONObject userJSON = JSON.parseObject(response);

			Integer errorCode = 0;

			if ((errorCode = userJSON.getInteger(Const.WEIXIN_RESP_ERRCODE_FIELD)) != null && errorCode != 0) {
				throw new BizHandleException("获取微信用户信息失败，返回异常！");
			}
			return converToWxUser(userJSON);

		} catch (Exception e) {
			LOG.error("queryUserInfo exception", e);
			return null;
		}
	}

	private WeiXinUser converToWxUser(JSONObject json) {
		if (json.get("errcode") != null) {
			return null;
		}
		WeiXinUser wxUser = new WeiXinUser();

		wxUser.setUnionId(json.getString(Const.WEIXIN_RESP_UNIONID_FIELD));
		wxUser.setOpenId(json.getString(Const.WEIXIN_RESP_OPENID_FIELD));
		wxUser.setNickName(json.getString(Const.WEIXIN_RESP_NICKNAME_FIELD));

		int sex = json.getIntValue(Const.WEIXIN_RESP_SEX_FIELD);
		wxUser.setSex((short) sex);

		wxUser.setCity(json.getString(Const.WEIXIN_RESP_CITY_FIELD));
		wxUser.setProvince(json.getString(Const.WEIXIN_RESP_PROVINCE_FIELD));
		wxUser.setCountry(json.getString(Const.WEIXIN_RESP_COUNTRY_FIELD));
		wxUser.setLanguage(json.getString(Const.WEIXIN_RESP_LANGUAGE_FIELD));
		wxUser.setHeadImgUrl(json.getString(Const.WEIXIN_RESP_HEADIMGURL_FIELD));

		int subscribe = json.getIntValue(Const.WEIXIN_RESP_SUBSCRIBE_FIELD);
		wxUser.setSubscribe(subscribe == 0 ? false : true);

		Long lsubscribe_time = json.getLong(Const.WEIXIN_RESP_SUBSCRIBE_TIME_FIELD);
		wxUser.setSubscribeTime(lsubscribe_time != null ? new Date(lsubscribe_time * 1000) : null);

		return wxUser;
	}
}
